import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../common/models/index.dart';
import '../../common/services/native_wechat_share_service.dart';
import '../../common/services/local_share_server_service.dart';
import '../../common/services/share_page_generator_service.dart';
import '../../common/api/share_api.dart';
import '../../common/utils/toast_util.dart';
import 'dart:developer' as developer;

/// 🧪 分享页面测试页面
/// 
/// 用于测试和演示分享页面功能
class ShareTestPage extends StatefulWidget {
  const ShareTestPage({Key? key}) : super(key: key);

  @override
  State<ShareTestPage> createState() => _ShareTestPageState();
}

class _ShareTestPageState extends State<ShareTestPage> {
  late NativeWeChatShareService _weChatService;
  late LocalShareServerService _shareServerService;
  
  bool _isServerRunning = false;
  String _serverUrl = '';
  
  // 测试活动数据
  final _testActivity = ActivityModel(
    id: '123',
    title: '台球搭子快来！',
    description: '我在玩真的发现了一个有趣的活动，快来看看吧！这是一个非常有趣的台球活动，欢迎大家参加。我们会在周末举办，地点在市中心的台球俱乐部。',
    imageUrl: 'http://app.playtruly.cn/images/user/3/20250913150202_2017237a.jpeg',
    location: '市中心台球俱乐部',
    date: DateTime.now().add(const Duration(days: 2)),
    organizer: UserModel(
      id: '1',
      name: '小明',
      avatarUrl: 'http://app.playtruly.cn/images/default/avatar.jpg',
    ),
    participants: 5,
    maxParticipants: 10,
    tags: ['台球', '运动', '社交'],
  );

  @override
  void initState() {
    super.initState();
    _initServices();
  }

  /// 初始化服务
  void _initServices() {
    _weChatService = Get.find<NativeWeChatShareService>();
    _shareServerService = Get.find<LocalShareServerService>();
    
    // 更新初始状态
    _updateServerStatus();
  }
  
  /// 更新服务器状态
  void _updateServerStatus() {
    setState(() {
      _isServerRunning = _shareServerService.isRunning;
      if (_isServerRunning) {
        _serverUrl = _shareServerService.generateActivityShareUrl(_testActivity.id);
      } else {
        _serverUrl = '';
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('🧪 分享页面测试'),
        backgroundColor: Colors.green,
        foregroundColor: Colors.white,
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 服务器状态卡片
            _buildServerStatusCard(),
            const SizedBox(height: 16),
            
            // 测试活动信息卡片
            _buildTestActivityCard(),
            const SizedBox(height: 16),
            
            // 分享功能测试卡片
            _buildShareTestCard(),
            const SizedBox(height: 16),
            
            // 高级功能测试卡片
            _buildAdvancedTestCard(),
          ],
        ),
      ),
    );
  }

  /// 构建服务器状态卡片
  Widget _buildServerStatusCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Icon(
                  _isServerRunning ? Icons.circle : Icons.circle_outlined,
                  color: _isServerRunning ? Colors.green : Colors.grey,
                  size: 12,
                ),
                const SizedBox(width: 8),
                Text(
                  '本地分享服务器',
                  style: Theme.of(context).textTheme.titleMedium?.copyWith(
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            Text(
              '状态: ${_isServerRunning ? "运行中" : "已停止"}',
              style: TextStyle(
                color: _isServerRunning ? Colors.green : Colors.grey,
                fontWeight: FontWeight.w500,
              ),
            ),
            if (_isServerRunning) ...[
              const SizedBox(height: 4),
              Text(
                '端口: ${_shareServerService.port}',
                style: const TextStyle(color: Colors.grey),
              ),
              const SizedBox(height: 4),
              Text(
                '测试URL: $_serverUrl',
                style: const TextStyle(color: Colors.blue, fontSize: 12),
              ),
            ],
            const SizedBox(height: 12),
            Row(
              children: [
                ElevatedButton(
                  onPressed: _isServerRunning ? null : _startServer,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.green,
                    foregroundColor: Colors.white,
                  ),
                  child: const Text('启动服务器'),
                ),
                const SizedBox(width: 8),
                ElevatedButton(
                  onPressed: _isServerRunning ? _stopServer : null,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.red,
                    foregroundColor: Colors.white,
                  ),
                  child: const Text('停止服务器'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建测试活动信息卡片
  Widget _buildTestActivityCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '📝 测试活动信息',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 12),
            _buildInfoRow('活动ID', _testActivity.id),
            _buildInfoRow('活动标题', _testActivity.title),
            _buildInfoRow('活动描述', _testActivity.description),
            _buildInfoRow('活动地点', _testActivity.location),
            _buildInfoRow('图片', _testActivity.imageUrl),
            _buildInfoRow('开始时间', _testActivity.date.toString()),
            _buildInfoRow('组织者', _testActivity.organizer.name),
          ],
        ),
      ),
    );
  }

  /// 构建分享功能测试卡片
  Widget _buildShareTestCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '🎨 分享功能测试',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 12),
            const Text(
              '测试新的分享页面系统功能',
              style: TextStyle(color: Colors.grey),
            ),
            const SizedBox(height: 16),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                ElevatedButton.icon(
                  onPressed: _testGenerateSharePage,
                  icon: const Icon(Icons.web),
                  label: const Text('生成分享页面'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    foregroundColor: Colors.white,
                  ),
                ),
                ElevatedButton.icon(
                  onPressed: _testPreviewSharePage,
                  icon: const Icon(Icons.preview),
                  label: const Text('预览分享页面'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.orange,
                    foregroundColor: Colors.white,
                  ),
                ),
                ElevatedButton.icon(
                  onPressed: _testWeChatShare,
                  icon: const Icon(Icons.share),
                  label: const Text('微信分享测试'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.green,
                    foregroundColor: Colors.white,
                  ),
                ),
                const SizedBox(height: 8),
                ElevatedButton.icon(
                  onPressed: _testAPIShare,
                  icon: const Icon(Icons.api),
                  label: const Text('API分享链接测试'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.purple,
                    foregroundColor: Colors.white,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建高级功能测试卡片
  Widget _buildAdvancedTestCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '⚙️ 高级功能测试',
              style: Theme.of(context).textTheme.titleMedium?.copyWith(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 12),
            const Text(
              '服务器管理和调试功能',
              style: TextStyle(color: Colors.grey),
            ),
            const SizedBox(height: 16),
            Wrap(
              spacing: 8,
              runSpacing: 8,
              children: [
                ElevatedButton.icon(
                  onPressed: _registerTestActivity,
                  icon: const Icon(Icons.app_registration),
                  label: const Text('注册测试活动'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.purple,
                    foregroundColor: Colors.white,
                  ),
                ),
                ElevatedButton.icon(
                  onPressed: _showServerStats,
                  icon: const Icon(Icons.analytics),
                  label: const Text('服务器统计'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.indigo,
                    foregroundColor: Colors.white,
                  ),
                ),
                ElevatedButton.icon(
                  onPressed: _clearServerCache,
                  icon: const Icon(Icons.clear_all),
                  label: const Text('清除缓存'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.grey,
                    foregroundColor: Colors.white,
                  ),
                ),
                ElevatedButton.icon(
                  onPressed: _testHealthCheck,
                  icon: const Icon(Icons.health_and_safety),
                  label: const Text('健康检查'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.teal,
                    foregroundColor: Colors.white,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 2),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: const TextStyle(
                fontWeight: FontWeight.w500,
                color: Colors.grey,
              ),
            ),
          ),
          Expanded(
            child: Text(
              value,
              style: const TextStyle(color: Colors.black87),
            ),
          ),
        ],
      ),
    );
  }

  /// 启动服务器
  Future<void> _startServer() async {
    try {
      ToastUtil.info('正在启动分享服务器...');
      
      final success = await _shareServerService.startServer();
      if (success) {
        ToastUtil.success('分享服务器启动成功');
        _updateServerStatus();
      } else {
        ToastUtil.error('分享服务器启动失败');
      }
    } catch (e) {
      ToastUtil.error('启动服务器失败: $e');
    }
  }

  /// 停止服务器
  Future<void> _stopServer() async {
    try {
      await _shareServerService.stopServer();
      ToastUtil.success('分享服务器已停止');
      _updateServerStatus();
    } catch (e) {
      ToastUtil.error('停止服务器失败: $e');
    }
  }

  /// 注册测试活动
  void _registerTestActivity() {
    _shareServerService.registerActivity(_testActivity);
    ToastUtil.success('测试活动已注册到分享服务器');
  }

  /// 测试生成分享页面
  Future<void> _testGenerateSharePage() async {
    try {
      ToastUtil.info('正在生成分享页面...');
      
      final shareUrl = 'http://localhost:8080/share/activity/${_testActivity.id}';
      final htmlContent = await SharePageGeneratorService.generateActivitySharePage(
        activity: _testActivity,
        shareUrl: shareUrl,
      );
      
      if (SharePageGeneratorService.validateHtmlContent(htmlContent)) {
        ToastUtil.success('分享页面生成成功');
        developer.log('📄 分享页面HTML长度: ${htmlContent.length} 字符');
      } else {
        ToastUtil.error('分享页面内容验证失败');
      }
    } catch (e) {
      ToastUtil.error('生成分享页面失败: $e');
    }
  }

  /// 测试预览分享页面
  Future<void> _testPreviewSharePage() async {
    try {
      if (!_isServerRunning) {
        ToastUtil.warning('请先启动分享服务器');
        return;
      }
      
      await _weChatService.previewActivitySharePage(
        activity: _testActivity,
        shareUrl: _serverUrl,
      );
      
      ToastUtil.success('分享页面预览已生成，请查看控制台');
    } catch (e) {
      ToastUtil.error('预览分享页面失败: $e');
    }
  }

  /// 测试微信分享
  Future<void> _testWeChatShare() async {
    try {
      if (!_isServerRunning) {
        ToastUtil.warning('请先启动分享服务器并注册测试活动');
        return;
      }
      
      final success = await _weChatService.shareActivityWithPage(
        activity: _testActivity,
        shareUrl: _serverUrl,
      );
      
      if (success) {
        ToastUtil.success('微信分享测试成功');
      } else {
        ToastUtil.error('微信分享测试失败');
      }
    } catch (e) {
      ToastUtil.error('微信分享测试失败: $e');
    }
  }

  /// 🔥 测试通过API获取分享链接（新功能）
  /// 对应MyApplication2项目的实现方式
  Future<void> _testAPIShare() async {
    try {
      ToastUtil.info('正在测试API分享链接获取...');
      
      // 测试通过API获取分享链接（使用MyApplication2格式）
      final shareResponse = await ShareApi.createActivityShare(
        activityTitle: _testActivity.title,
        activityText: _testActivity.description,
        activityImages: _testActivity.imageUrl.isNotEmpty ? [_testActivity.imageUrl] : [],
        userNickname: '测试用户',
        userGender: '保密',
        userCity: '测试城市',
        userAvatarUrl: 'http://app.playtruly.cn/system/avatar.jpg',
      );
      
      if (shareResponse.isSuccess && shareResponse.data?.shareUrl.isNotEmpty == true) {
        final shareUrl = shareResponse.data!.shareUrl;
        final shareId = shareResponse.data!.shareId;
        
        ToastUtil.success('✅ API分享链接获取成功');
        
        // 显示获取到的分享信息
        Get.dialog(
          AlertDialog(
            title: const Text('🔗 API分享链接测试结果'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('✅ 状态: ${shareResponse.status}'),
                const SizedBox(height: 8),
                Text('🆔 分享ID: ${shareId ?? "无"}'),
                const SizedBox(height: 8),
                Text('🌐 分享链接:'),
                const SizedBox(height: 4),
                Container(
                  padding: const EdgeInsets.all(8),
                  decoration: BoxDecoration(
                    color: Colors.grey[100],
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: SelectableText(
                    shareUrl,
                    style: const TextStyle(
                      fontSize: 12,
                      fontFamily: 'monospace',
                    ),
                  ),
                ),
                const SizedBox(height: 12),
                const Text(
                  '📝 说明: 这是通过后端API动态生成的分享链接，与MyApplication2项目的实现方式一致。',
                  style: TextStyle(fontSize: 12, color: Colors.grey),
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Get.back(),
                child: const Text('关闭'),
              ),
              ElevatedButton(
                onPressed: () {
                  Get.back();
                  // 测试使用API获取的分享链接进行微信分享
                  _testWeChatShareWithAPIUrl(shareUrl);
                },
                child: const Text('测试微信分享'),
              ),
            ],
          ),
        );
      } else {
        ToastUtil.error('❌ API分享链接获取失败: ${shareResponse.message}');
        
        // 显示错误信息
        Get.dialog(
          AlertDialog(
            title: const Text('❌ API分享链接测试失败'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('状态: ${shareResponse.status}'),
                const SizedBox(height: 8),
                Text('错误信息: ${shareResponse.message ?? "未知错误"}'),
                const SizedBox(height: 12),
                const Text(
                  '💡 提示: 可能是服务器接口尚未实现，或网络连接问题。',
                  style: TextStyle(fontSize: 12, color: Colors.orange),
                ),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Get.back(),
                child: const Text('关闭'),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      ToastUtil.error('API分享链接测试异常: $e');
      
      // 显示异常信息
      Get.dialog(
        AlertDialog(
          title: const Text('💥 API分享链接测试异常'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('异常信息: $e'),
              const SizedBox(height: 12),
              const Text(
                '🔧 可能的原因:\n• 网络连接问题\n• 服务器接口未实现\n• 加密参数错误',
                style: TextStyle(fontSize: 12, color: Colors.red),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Get.back(),
              child: const Text('关闭'),
            ),
          ],
        ),
      );
    }
  }

  /// 使用API获取的分享链接测试微信分享
  Future<void> _testWeChatShareWithAPIUrl(String apiShareUrl) async {
    try {
      ToastUtil.info('正在使用API分享链接测试微信分享...');
      
      final success = await _weChatService.shareActivityWithPage(
        activity: _testActivity,
        shareUrl: apiShareUrl, // 使用API获取的分享链接
      );
      
      if (success) {
        ToastUtil.success('✅ 使用API分享链接的微信分享测试成功');
      } else {
        ToastUtil.error('❌ 使用API分享链接的微信分享测试失败');
      }
    } catch (e) {
      ToastUtil.error('使用API分享链接的微信分享测试失败: $e');
    }
  }

  /// 显示服务器统计信息
  void _showServerStats() {
    final stats = _shareServerService.getServerStats();
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('📊 服务器统计信息'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('运行状态: ${stats['isRunning'] ? "运行中" : "已停止"}'),
            Text('服务器地址: ${stats['serverUrl']}'),
            Text('缓存活动数: ${stats['cachedActivities']}'),
            Text('缓存页面数: ${stats['cachedPages']}'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  /// 清除服务器缓存
  void _clearServerCache() {
    _shareServerService.clearCache();
    ToastUtil.success('服务器缓存已清除');
  }

  /// 测试健康检查
  Future<void> _testHealthCheck() async {
    if (!_isServerRunning) {
      ToastUtil.warning('分享服务器未运行');
      return;
    }
    
    try {
      // 这里可以添加HTTP请求测试健康检查端点
      // 由于是本地测试，我们直接显示服务器状态
      ToastUtil.success('服务器健康检查通过');
    } catch (e) {
      ToastUtil.error('健康检查失败: $e');
    }
  }
}
